<?php
class LSourceMessage extends CActiveRecord
{
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return 'LSourceMessage';
    }

    public function rules()
    {

        return array(
                array('category, message', 'required'),
                array('message', 'unique'),
                array('category', 'numerical', 'integerOnly'=>true),
                array('id, category, message', 'safe', 'on'=>'search'),
        );
    }

    public function relations()
    {
        return array(
                'lMessages' => array(self::HAS_MANY, 'LMessage', 'message_source_id'),
                'category0' => array(self::BELONGS_TO, 'LCategorySourceMessage', 'category'),
        );
    }

    public function attributeLabels()
    {
        return array(
                'id'        => 'ID',
                'category'  => Yii::t('language', 'Категория меток словаря'),
                'message'   => Yii::t('language', 'Языковая метка'),
        );
    }

    public static function dropDownItemsAll(){
        $items= Array();
        $model = self::model()->findAll();
        foreach ($model as $value) {
            $items[$value->id] = $value->message;
        }
        return $items;
    }
    
    public static function getAvailableTranslations($id){
        $command=Yii::app()->db->createCommand()
                ->select('m.id translation_id, l.id language_id, name, message_source_id, name, translation')
                ->from('LMessage m')
                ->join('Language l', 'm.language = l.id')
                ->where('message_source_id=:id')
                ->bindParam(':id',$id)
                ->queryAll();
        
        $count_language = Language::countLang()-1;

        $language_for_item = Array();

        foreach ($command as $key => $value) {
            $language_for_item[] = $value['language_id'];
            $view .= CHtml::link($value['name'].' - '.$value['translation'],array('/language/lmessage/update','id'=>$value['translation_id'])).'<br>';
        }
        
        if ($count_language > count($command)){
            foreach (Language::allExcept($language_for_item) as $value) {
                $view .= CHtml::link($value['name'].' - Нет перевода',array('/language/lmessage/create','language_id'=>$value['id'],'message_source_id'=>$id),array('class'=>'warning')).'<br>';
       
            }
        }

        return $view;
    }

    public function search()
    {	
        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('category',$this->category);
        $criteria->compare('message',$this->message,true);

        return new CActiveDataProvider($this, array(
                'criteria'=>$criteria,
        ));
    }
}